package com.samp.bblock.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	
	private static final String REQUEST_METHOD_POST = "POST";
	private static final String REQUEST_METHOD_GET = "GET";
	private static final Integer REPONSE_SUCESS = 200;
	
    private static RequestBuilder buildRequestBuilder(String method,Map<String,String>map){
        if( method.equalsIgnoreCase(REQUEST_METHOD_GET)){
            return RequestBuilder.get();
        }else if(method.equalsIgnoreCase(REQUEST_METHOD_POST)){
            RequestBuilder requestBuilder= RequestBuilder.post();
            if(map!=null && map.size()>0){
                for(Map.Entry<String,String>mapentry:map.entrySet())
                requestBuilder.addParameter(mapentry.getKey(),mapentry.getValue());
            }
            return requestBuilder;
        } 
        throw new IllegalArgumentException("illegal http method"+method);
    }
    
    private static String transferStreamToStr(InputStream inputStream) throws IOException{
    	int k;
        StringBuffer sbf=new StringBuffer();
        byte[ ]bytes=new byte[1024];
        while((k=inputStream.read(bytes))!=-1){
            sbf.append(new String(bytes,0,k));
        }
        return sbf.toString();
    }
    
    public static boolean executeGetMethod(String[] urls){
    	if( urls == null || urls.length == 0 ){
    		return false;
    	}
    	HttpClientBuilder httpClientBuilder= HttpClients.custom();
		CloseableHttpClient closeableHttpClient=httpClientBuilder.build();
		CloseableHttpResponse response = null;
		RequestBuilder requestBuilder=buildRequestBuilder(REQUEST_METHOD_GET, null);
		boolean success = true;
		for( String url : urls ){
			requestBuilder.setUri(url);
	        HttpUriRequest httpUriRequest=requestBuilder.build();
	        try {
				response=closeableHttpClient.execute(httpUriRequest);
				Integer status = response.getStatusLine().getStatusCode();
				if( !REPONSE_SUCESS.equals(status) ){
					success = false;
				}
				logger.info("==responseStatus:"+(response.getStatusLine().getStatusCode()));
				InputStream inputStream=response.getEntity().getContent();
				logger.info("==responseText:"+(transferStreamToStr(inputStream)));
			} catch (Exception e) {
				success = false;
				logger.error("error when execute url : "+url, e);
			}
		}
		try {
			closeableHttpClient.close();
		} catch (IOException e) {
			logger.error("error when close client ", e);
		}
		if( response != null ){
			try {
				response.close();
			} catch (IOException e) {
				logger.error("error when close response", e);
			}
		}
		return success;
    }
    
    public static void main(String[] args) {
    	boolean falg = executeGetMethod(new String[]{"http://www.baidu.com"})	;
    	System.out.println(falg);
	}
    
}
